<template>
  <div id="Orders" v-loading="loading">
    <v-tableTitle
      :btnConfig="btnConfig"
      :tableSelectData="tableSelectData"
      :title="$t('out.outbound')"
      @del="del"
      @exportPo="exportPo"
      @newCreate="newCreate"
      @downloadExcelFile_LineStop="downloadExcelFile_LineStop"
      @allocation="allocation"
      @cancel="cancel"
      @grant="grant"
      @revocation="revocation"
      @order="order"
      @deliver="deliver"
      @replenish="replenish"
      @printJHD="printJHD"
      @handleDownErrorFile="exceptionFileUrl"
      @handleDownTemplate="downloadExcelFile"
    ></v-tableTitle>
    <GTable
      ref="table"
      :hasCheck="true"
      :hasEdit="true"
      :showSummary="true"
      dateKey="orderdate"
      api="queryAllOrdersList"
      :otherHeight="0"
      :columnConfig="columnConfig"
      @selection-change="selectData"
      @setdialog="setdialog"
    >
    </GTable>
  </div>
</template>

<script type="text/ecmascript-6">
import tableTitle from "commons/TableTitle";
import table from "commons/Table";
import baseMixin from "@/mixins/BaseMixin";
import config from "./Config";
import print from "@/assets/js/print";
import agGridBaseMixin from "@/mixins/AgGridBaseMixin";

export default {
  name: "orders",
  mixins: [baseMixin, config,agGridBaseMixin],
  data () {
    return {
      columnConfig:{ menu_id: 21, menu_code:"orders", menu_list_code:"Orders"},
      // 出库订单
      importType: 10311,
      // 导入可视化 end
      loading: false,
      defaultColDef: {
      },
      tableData: [],
      pageSize: 10,
      page: 1,
      total: 0,
      tableSelectData: [],
      tableSearhData: {},
      poiStatus: false
    };
  },
  computed: {
    btnConfig () {
      return [
        { type: "file", certigier: this.uploadStatus||!this.btnPermNameList.includes('WM020101'), label: this.$t('common.import'), invalid: "file",importType:'10311',importUrl:"importOrder",downTemplate:"handleDownTemplate",sheetKey:"orderdetailList" },
        // {label: this.$t('config.importTemDownload'), certigier: this.poiStatus||!this.btnPermNameList.includes('WM020102'), invalid: "downloadExcelFile"},
        { label: this.$t('common.export'), certigier: this.downloadStatus||!this.btnPermNameList.includes('WM020103'), disabled: true, invalid: "exportPo" },
        { label: this.$t('common.create'), certigier: this.newStatus||!this.btnPermNameList.includes('WM020104'), invalid: "newCreate" },
        { label: this.$t('common.delete'), certigier: this.deleteStatus||!this.btnPermNameList.includes('WM020105'), disabled: true, invalid: "del" },
        { label: this.$t('common.cancel'), certigier: this.deleteStatus||!this.btnPermNameList.includes('WM020106'), disabled: true, invalid: "cancel" },
        {
          type: "more", label: this.$t('common.moreMenu'), certigier: !this.btnPermNameList.includes('WM020107'),  invalid: "down", btnConfig: [
            { label: this.$t('out.allocation'), certigier: this.allocationStatus||!this.btnPermNameList.includes('WM020108'), disabled: true, invalid: "allocation" },
            /*{ label: this.$t('out.grant'), certigier: this.allocationStatus, disabled: true, invalid: "grant" },*/
            { label: this.$t('out.revocation'), certigier: this.allocationStatus||!this.btnPermNameList.includes('WM020109'), disabled: true, invalid: "revocation" },
            { label: this.$t('out.allPick'), certigier: this.allocationStatus||!this.btnPermNameList.includes('WM020110'), disabled: true, invalid: "order" },
            { label: this.$t('out.allShip'), certigier: this.allocationStatus||!this.btnPermNameList.includes('WM020111'), disabled: true, invalid: "deliver" },
            // 禅道【2613】【 出库订单-订单补货，点击订单补货按钮报错】缺失存储过程，先隐藏功能
            // { label: this.$t('out.replenish'), certigier: this.allocationStatus||!this.btnPermNameList.includes('WM020112'), disabled: true, invalid: "replenish" },
            {label: this.$t('out.printJHD'), certigier: this.deleteStatus||!this.btnPermNameList.includes('WM020113'), disabled: true, invalid: "printJHD"},

          ]
        },
       { type: "file", certigier: this.uploadStatus||!this.btnPermNameList.includes('WM020114'), label: this.$t('out.importstop'), invalid: "file",importType:'10314',importUrl:"importLineStop",downTemplate:"downloadExcelFile_LineStop"},
      //  {label: this.$t('out.downstoptem'), certigier: this.poiStatus||!this.btnPermNameList.includes('WM020115'), invalid: "downloadExcelFile_LineStop"}
      ]
    }
  },
  created () {
  },
  methods: {
    exceptionFileUrl(exceptionUrl,importType) {

      console.log("exceptionFileUrl = %o", 1);
      const data = [{
        exceptionFileUrl: exceptionUrl
      }];

      // 异常下载配置
        let exceptionFileName = "出库订单导入模板异常文件.xls";
      if(importType == 10311){
          exceptionFileName = "出库订单导入模板异常文件.xls";
      }else if(importType == 10314){
          exceptionFileName = "线路停靠点导入模板异常文件.xls";
      }
      let urlConf = {responseType: 'blob'};
      let url = '/comExcelImportResult/downloadExceptionFile';
      let options = {type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document;charset=utf-8'};

      try {
        this.$api.post(url, data, urlConf).then(res => {
          let blobParts = [res.data];
          if (window.navigator.msSaveBlob) {
            const blobObject = new Blob(blobParts);
            window.navigator.msSaveBlob(blobObject, exceptionFileName);
          } else {
            let tagName = 'a';
            const blob = new Blob(blobParts, options);
            const downloadElement = document.createElement(tagName);
            // 创建下载的链接
            const href = window.URL.createObjectURL(blob);
            downloadElement.style.display = 'none';
            downloadElement.href = href;
            // 下载后文件名
            downloadElement.download = exceptionFileName;
            document.body.appendChild(downloadElement);
            // 点击下载
            downloadElement.click();
            // 下载完成移除元素
            document.body.removeChild(downloadElement);
            // 释放掉blob对象
            window.URL.revokeObjectURL(href);
          }
          this.importVisualDialogFlag = false;
        });
      } catch (e) {
        this.$message.error(e);
      } finally {
        
      }
    },
    replenish (data) {
      data.forEach(async (item, index) => {
        try {
          let res = await this.$api.get(`/ordersReplenish/${item.orderkey}`);
          
            this.$message.success(res.returnMgr);
            // let page = sessionStorage.getItem('page');
            // this.getTableData(page, this.tableSearhData);
            this.$refs.table.getTableData();
          
        } catch (e) {
          this.$message.error(e);
        } finally {
          this.$refs.table.delSelectData(item, index);
        }
      });
    },
    deliver (data) {
      data.forEach(async (item, index) => {
        try {
          let res = await this.$api.get(`/ordersDeliverAll/${item.orderkey}`);
          
            this.$message.success(res.returnMgr);
            // let page = sessionStorage.getItem('page');
            // this.getTableData(page, this.tableSearhData);
            this.$refs.table.getTableData();
          
        } catch (e) {
          this.$message.error(e);
        } finally {
          this.$refs.table.delSelectData(item, index);
        }
      });
    },
    order (data) {
      data.forEach(async (item, index) => {
        try {
          let res = await this.$api.get(`/ordersPickingAll/${item.orderkey}`);
          
            this.$message.success(res.returnMgr);
            // let page = sessionStorage.getItem('page');
            // this.getTableData(page, this.tableSearhData);
            this.$refs.table.getTableData();
          
        } catch (e) {
          this.$message.error(e);
        } finally {
          this.$refs.table.delSelectData(item, index);
        }
      });
    },
    revocation (data) {
      data.forEach(async (item, index) => {
        try {
          let res = await this.$api.get(`/ordersRevokeAllocate/${item.orderkey}`);
          
            this.$message.success(res.returnMgr);
            // let page = sessionStorage.getItem('page');
            // this.getTableData(page, this.tableSearhData);
            this.$refs.table.getTableData();
          
        } catch (e) {
          this.$message.error(e);
        } finally {
          this.$refs.table.delSelectData(item, index);
        }
      });
    },
    allocation (data) {
      data.forEach(async (item, index) => {
        try {
          let res = await this.$api.post(`/allocateByOrderkey/${item.orderkey}/${this.$store.state.wms}`);
          
            this.$message.success(res.returnMgr);
            // let page = sessionStorage.getItem('page');
            // this.getTableData(page, this.tableSearhData);
            this.$refs.table.getTableData();
            this.$refs.table.delSelectData(item, index);
        } catch (e) {
          this.$message.error(e);
        } finally {
          this.$refs.table.delSelectData(item, index);
        }
      });

    },
    grant (data) {
      data.forEach(async (item, index) => {
        try {
          let res = await this.$api.get(`/ordersReleaseTask/${item.orderkey}`);
          
            this.$message.success(res.returnMgr);
            // let page = sessionStorage.getItem('page');
            // this.getTableData(page, this.tableSearhData);
            this.$refs.table.getTableData();
          
        } catch (e) {
          this.$message.error(e);
        } finally {
          this.$refs.table.delSelectData(item, index);
        }
      });
    },
    //新建
    async newCreate () {
      this.$router.push({ name: 'ordersDeawer',query:{newFlag:true} });
      // try {
      //   // let res = await this.$api.get('/codeLookup/nCounter/ORDER');
      //   // 2022-10-28 修改单号编码取值方式 hkjun
      //   let numberType = 11703;
      //   let res = await this.$api.get("/sysNumberRule/getSysNumberByType/"+numberType);
      //   
      //     this.$store.commit("setRouteId", res.data.data);
      //     this.$store.commit("setNewFlag", true);
      //     this.$router.push({ name: 'ordersDeawer' });
      //   }
      // } catch (e) {
      //   this.$message.error(e);
      // }
    },
    async cancel (data) {
      try {
        let res = await this.$api.post(`/tichuOrders`, data);
        
          this.$message.success(res.returnMgr);
          // let page = sessionStorage.getItem('page');
          // this.getTableData(page, this.tableSearhData);
          this.$refs.table.getTableData();
          
        
      } catch (e) {
        this.$message.error(e);
      }
    },
    //导出
    async exportPo (data) {
      try {
        let arr = [];
        data.forEach((item, index) => {
          arr.push({ "orderkey": item.orderkey });
        })
        let res = await this.$api.post('/exportOrders', arr, { responseType: 'blob' })
        if (window.navigator.msSaveBlob) {
          var blobObject = new Blob([res.data]);
          window.navigator.msSaveBlob(blobObject, 'orders表.xls');
        } else {
          var blob = new Blob([res.data], { type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document;charset=utf-8' });
          var filename = 'orders表.xls';
          var downloadElement = document.createElement('a');
          var href = window.URL.createObjectURL(blob); //创建下载的链接
          downloadElement.style.display = 'none';
          downloadElement.href = href;
          downloadElement.download = filename; //下载后文件名
          document.body.appendChild(downloadElement);
          downloadElement.click(); //点击下载
          document.body.removeChild(downloadElement); //下载完成移除元素
          window.URL.revokeObjectURL(href); //释放掉blob对象
        }
      } catch (e) {
        this.$message.error(e);
      }
    },
    async batchImport (key, batchImportData, callEnds) {

      let res = await this.$api.post(`/importOrder/${this.importType}/${key}`, batchImportData);
      let resData = res.data.data;
      if (resData !== undefined && resData !== null) {

          // 调用导入页面 = start /////////////////////////////
          let failedCount = resData.value.failedCount;
          let successCount = resData.value.successCount;
          let exceptionFileUrl = resData.value.exceptionFileUrl;
          if (failedCount !== 0) {
            this.failedCount = failedCount;
            this.exceptionUrl = exceptionFileUrl;
            this.successCount = successCount;
            this.importStatus = 3;
          } else {
            this.importStatus = 2;
            this.successCount = successCount;
          }
          // 调用导入页面 =  end //////////////////////////////
        } else {
          if (callEnds) {
            this.$message.error(resData.desc);
            this.importVisualBeforeClose();
          }
        }
    },
    async downloadExcelFile(data) {
      try {
        let xls = "出库订单导入模板.xls";
        let url = "/downloadExcelFile/" + xls;
        let res = await this.$api.post(url, data, {responseType: 'blob'})
        if (window.navigator.msSaveBlob) {
          var blobObject = new Blob([res.data]);
          window.navigator.msSaveBlob(blobObject, xls);
        } else {
          var blob = new Blob([res.data], {type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document;charset=utf-8'});
          var filename = '出库订单导入模板.xls';
          var downloadElement = document.createElement('a');
          var href = window.URL.createObjectURL(blob); //创建下载的链接
          downloadElement.style.display = 'none';
          downloadElement.href = href;
          downloadElement.download = filename; //下载后文件名
          document.body.appendChild(downloadElement);
          downloadElement.click(); //点击下载
          document.body.removeChild(downloadElement); //下载完成移除元素
          window.URL.revokeObjectURL(href); //释放掉blob对象
        }
      } catch (e) {
        this.$message.error(e);
      } finally {
        if (data.length !== 0) {
          
        }
      }
    },
    //导入
    upFileBak (fileData) {

      let file = fileData.get("file");
      if (!file) {
        return this.$message.error(this.$t('msg.msg17'));
      } else {
        this.importType = 10311;
        let url = `/sysExcelImportRule/selectExcelImportDefineByRuleImportDataType/${this.importType}`;
        this.$api.post(url, {}).then((res) => {
          console.log("获取模板结果 = %o", res);

            // 第几行开始读 excel解析成json需要key值 故从前一行开始读
            let range = res.data.readLineNum - 1;
            let sheets = res.data.templateSheetType;
            this.$refs.table.excelManySheetParsing(file, range).then((map) => {

              console.log("读取文件数据结果 = %o", map);
              let masterSheet = map.masterSheet;
              // 验证模板sheetType配置和导入文件是否一致 sheets > 1表示存在对象数据
              let isSubSheet = map.isSubSheet;
              if (!(isSubSheet && sheets > 1)) {
                return this.$message.error(this.$t('msg.msg60'));
              }

              let size = map.masterSize;
              if (size > 0) {

                // 调用导入页面 = start /////////////////////////////
                this.importStatus = 1;
                this.totalCount = size;
                this.importVisualDialogFlag = true;
                // 调用导入页面 =  end //////////////////////////////

                // 拿取主sheet的关联字段
                let ele = "关联编号";
                let subSheet = "subSheet";
                masterSheet.forEach((item) => {

                  // 初始化第一个sheet子表对象属性
                  item.orderdetailList = [];
                  for (let i = 0; i < map.subSheetSize; i++) {

                    let subName = subSheet + (i + 1);
                    map[subName].forEach((x) => {

                      // 验证是否归属主对象元素
                      if (item[ele] === x[ele]) {
                        // 添加第一个sheet子表对象属性
                        if (i === 0) {
                          item.orderdetailList.push(x);
                        }
                      }
                    });
                  }
                });

                let num = 0;
                let arrayData = new Array();
                let excelImportSize = 100;
                const key = this.$refs.table.uuid();
                console.log("uuid = %o", key);

                for (const item of masterSheet) {

                  const index = masterSheet.indexOf(item);
                  num = index + 1;
                  let callEnds = num === size;
                  let i = num % excelImportSize;
                  arrayData[i] = item;
                  if ((num % excelImportSize) === 0 || callEnds) {

                    fileData.set('arrayData', JSON.stringify(arrayData));
                    fileData.set('total', size);

                    // 调用导入页面 = start /////////////////////////////
                    // 验证无效null元素
                    let i = 0;
                    arrayData.forEach((item => {
                      if (item !== null) {
                        i += 1;
                      }
                    }))
                    this.beforeNumber = size - (i + this.afterNumber);
                    this.afterNumber += i;
                    // 调用导入页面 =  end //////////////////////////////

                    // 当数量满一次导入数量时 或数量等于导入的数量时 发送给后端
                    console.log("发送给后端数据集 = %o", arrayData);
                    this.batchImport(key, fileData, callEnds);
                    // 清空传入的数据
                    arrayData = new Array();
                  }
                }
              } else {
                return this.$message.error(this.$t('msg.msg61'));
              }
            })
        })
      }
    },
    //出库线路停靠点模板下载
    async downloadExcelFile_LineStop(data) {
      console.log("............");
        try {
            let xls = "线路停靠点导入模板.xls";
            let url = "/downloadExcelFile/" + xls;
            let res = await this.$api.post(url, {}, {responseType: 'blob'})
            console.log("window.navigator.msSaveBlob = %o",window.navigator.msSaveBlob);
            if (window.navigator.msSaveBlob) {
                var blobObject = new Blob([res.data]);
                window.navigator.msSaveBlob(blobObject, xls);
            } else {
                var blob = new Blob([res.data], {type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document;charset=utf-8'});
                var filename = xls;
                var downloadElement = document.createElement('a');
                var href = window.URL.createObjectURL(blob); //创建下载的链接
                downloadElement.style.display = 'none';
                downloadElement.href = href;
                downloadElement.download = filename; //下载后文件名
                document.body.appendChild(downloadElement);
                downloadElement.click(); //点击下载
                document.body.removeChild(downloadElement); //下载完成移除元素
                window.URL.revokeObjectURL(href); //释放掉blob对象
            }
        } catch (e) {
            this.$message.error(e);
        } finally {
            if (data.length !== 0) {
                
            }
        }
    },
    //选中的内容
    selectData (data) {
      this.tableSelectData = data;
    },
    //删除
    async del (data) {
      try {
        let res = await this.$api.post(`/deleteOrders`, data);
        
          this.$message.success(res.returnMgr);
          // let page = sessionStorage.getItem('page');
          // this.getTableData(page, this.tableSearhData);
          this.$refs.table.getTableData();
          
        
      } catch (e) {
        this.$message.error(e);
      }
    },
    // async getTableData (page, data) {
    //   try {
    //     this.loading = true;
    //     let res = await this.$api.post(`/queryOrdersList/${page}`, data);
    //     
    //       this.tableData = res.page.list;
    //       this.page = res.page.curpage;
    //       this.pageSize = res.page.pageSize;
    //       this.total = res.page.total;
    //     } else {
    //       this.$message.error(res.returnMgr);
    //     }
    //   } catch (e) {
    //     this.$message.error(e);
    //   } finally {
    //     this.loading = false;
    //   }
    // },
    //搜索的值
    searhData (data, up) {
      if (!up) {
        this.tableSearhData = data;
      } else {
        this.tableSearhData = data;
        // this.getTableData(1, this.tableSearhData);
      }
    },
    //设置弹框
    setdialog (data) {
      // this.$store.commit("setRouteData", data);
      this.$router.push({ name: 'ordersDeawer',query:data });
    },
    async printJHD (data) {
      for(let i = 0; i < data.length;i++) {
        print.bcgrfprint("ORDERJHD", data[i].orderkey);
      }
    },
  },
  mounted () {
    ;
    this.$store.commit("setSkip", {});
    this.$store.commit("setRouteId", '');
    this.$store.commit("setNewFlag", false);
    this.$store.commit("setRouteData", {});
    this.$store.commit("setDetailsNew", false);
    this.$store.commit("setTemporary", "");
    // this.getTableData(1, {});
  },
  watch: {
    tableSelectData (data) {
      if (this.permissionStatus) {
        if (data.length > 0) {
          this.deleteStatus = this.downloadStatus = false;
          this.allocationStatus = this.fafangStatus = false;
          this.deliverStatus = this.allPickStatus = this.allShipStatus = false;
        } else {
          this.deleteStatus = this.downloadStatus = true;
          this.allocationStatus = this.fafangStatus = true;
          this.deliverStatus = this.allPickStatus = this.allShipStatus = true;
        }
      }
    }
  },
  components: {
    "v-tableTitle": tableTitle,
    "v-table": table,
  }
};
</script>

<style scoped>
#Orders {
  width: 100%;
  height: 99%;
  padding-top: 6px;
}
</style>
